#!/usr/bin/env bash

# 获取域名的nginx配置.
# $1 域名 $2 存放路径
function get_nginx() {
    # 参数校验
    if [ -z "$1" ] || [ -z "$2" ]; then
        echo "cert-helper.sh get_nginx <域名> <存放路径>"
        exit
    fi
    # 打印配置
    echo "
server {
    listen 443 ssl;
    server_name ${1};

    ssl_certificate ${2}/${1}.crt;
    ssl_certificate_key ${2}/${1}.key;
    ssl_session_timeout 5m;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;

    # 你的剩余配置...
}
server {
    listen 80;
    server_name ${1};

    location /.well-known/acme-challenge/ {
        alias $(pwd)/challenges/${1}/;
        try_files \$uri =404;
    }

    location / {
        return 301 https://\$server_name\$request_uri;
    }
}
    "
}

# 获取后续刷新证书的cron配置
# $1 域名 $2 存放路径
function get_cron() {
    # 参数校验
    if [ -z "$1" ] || [ -z "$2" ]; then
        echo "cert-helper.sh get_cron <域名> <存放路径>"
        exit
    fi
    # 打印配置
    echo "
# 每个月运行一次, 刷新 ${1} 的证书
0 0 1 * *  root     bash $(pwd)/cert-helper.sh refresh ${1} ${2} 2>&1 >> $(pwd)/cert-tool.log
    "
}

# 刷新证书
# $1 域名 $2 存放路径
function refresh() {
    if [ -z "$1" ] || [ -z "$2" ]; then
        echo "cert-helper.sh refresh <域名> <存放路径>"
        exit
    fi
    if [ ! -e "$2" ]; then
        echo "路径不存在: $2"
        exit
    fi
    echo "当前时间: $(date '+%Y-%m-%d %H:%M:%S')"
    # 生成证书
    echo "即将为 ${1} 生成证书"
    bash gen-cert.sh "$1"
    # 迁移
    echo "迁移证书"
    # shellcheck disable=SC2216
    yes | cp "cert/${1}.key" "./cert/${1}.crt" "$2"
    # 刷新nginx
    echo "刷新nginx"
    nginx -s reload
    echo "证书刷新完成"
}


# 脚本所在目录
function curDir ( ) {
  if [ "${0%/*}" != "${0##*/}" ]
  then
      echo "${0%/*}"
  else
      echo "."
  fi
}

# 初始化脚本工作目录
cd "$(curDir)" || exit
# 执行命令
case $1 in
get_nginx)
  get_nginx "$2" "$3"
  ;;
refresh)
  refresh "$2" "$3"
  ;;
get_cron)
    get_cron "$2" "$3"
  ;;
*)
  echo "cert-helper.sh get_nginx|refresh|get_cron"
  ;;
esac